package com.clover.framework.utils;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FileUtil {
	public static void main(String[] args) {
		String dirName = "432f/fdas/theme/16/123.jpg";// 创建目录
		System.out.println(dirName.substring(dirName.indexOf("theme")));
	}

	/**
	 * @param folderPath 文件路径 (只删除此路径的最末路径下所有文件和文件夹)
	 */
	public static void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // 删除空文件夹
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除指定文件夹下所有文件
	 * @param path 文件夹完整绝对路径
	 */
	public static boolean delAllFile(String path) {
		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isDirectory()) {
			return flag;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]); // 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]); // 再删除空文件夹
				flag = true;
			}
		}
		return flag;
	}

	/**
	 * 创建目录 
	 * @param destDirName 目标目录名
	 * @return 目录创建成功返回true，否则返回false
	 */
	public static boolean createDir(String destDirName) {
		File dir = new File(destDirName);
		if (dir.exists()) {
			return false;
		}
		if (!destDirName.endsWith(File.separator)) {
			destDirName = destDirName + File.separator;
		}
		if (dir.mkdirs()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 删除文件 -- 不包含文件夹
	 * @param path
	 */
	public static void delFile(String path) {
		try {
			java.io.File file = new java.io.File(path);
			if (file.exists() && file.isFile()) {
				file.delete();
			}
		} catch (Exception e) {
			System.out.println("删除文件操作出错");
			e.printStackTrace();
		}
	}

	/**
	 * 获取文件夹中的所有文件 不包括子目录 Add By mashanlin 2015-06-26
	 * @param path 返回路径
	 */
	public static List<String> getAllFile(String path) {
		File file = new File(path);
		List<String> list = new ArrayList<String>();
		File[] tempList = file.listFiles();
		System.out.println("该目录下对象个数：" + tempList.length);
		for (int i = 0; i < tempList.length; i++) {
			if (tempList[i].isFile()) {
				System.out.println("文     件：" + tempList[i]);
				list.add(tempList[i].getPath());
			}
			/*
			 * if (tempList[i].isDirectory()) {
			 * System.out.println("文件夹："+tempList[i]); }
			 */
		}
		return list;
	}

	/**
	 * 根据后缀名分类文件 Add By mashanlin 2015-07-18
	 * @param suffix 文件后缀名
	 * @return
	 */
	public static String getFileType(String suffix) {
		String fileType = "";
		if (StringUtils.isEmpty(suffix))
			return fileType;
		if (suffix.startsWith("."))
			suffix = suffix.substring(1);

		suffix = suffix.toLowerCase();

		String image = "gif,jpg,jpeg,png,bmp";
		String flash = "swf,flv";
		String rar = "rar,zip,gz,bz2";
		String media = "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb";
		String file = "htm,html,pdf,xml";
		String office = "doc,docx,ppt,pptx,xls,xlsx";
		String txt = "txt,rtf,ini";
		// 图片格式
		if (Arrays.asList(image.split(",")).contains(suffix))
			return "image";

		// flash 格式
		if (Arrays.asList(flash.split(",")).contains(suffix))
			return "flash";

		// 压缩格式
		if (Arrays.asList(rar.split(",")).contains(suffix))
			return "rar";

		// 多媒体格式
		if (Arrays.asList(media.split(",")).contains(suffix))
			return "media";

		// office 文档格式
		if (Arrays.asList(office.split(",")).contains(suffix))
			return "office";

		// file 文档格式
		if (Arrays.asList(file.split(",")).contains(suffix))
			return "file";

		// 文本格式
		if (Arrays.asList(txt.split(",")).contains(suffix))
			return "txt";

		return suffix;
	}

	/**
	 * 读取到字节数组0
	 * 
	 * @param filePath
	 *            //路径
	 * @throws IOException
	 */
	public static byte[] getContent(String filePath) throws IOException {
		File file = new File(filePath);
		long fileSize = file.length();
		if (fileSize > Integer.MAX_VALUE) {
			System.out.println("file too big...");
			return null;
		}
		FileInputStream fi = new FileInputStream(file);
		byte[] buffer = new byte[(int) fileSize];
		int offset = 0;
		int numRead = 0;
		while (offset < buffer.length && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
			offset += numRead;
		}
		// 确保所有数据均被读取
		if (offset != buffer.length) {
			throw new IOException("Could not completely read file " + file.getName());
		}
		fi.close();
		return buffer;
	}

	/**
	 * 读取到字节数组1
	 * 
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public static byte[] toByteArray(String filePath) throws IOException {

		File f = new File(filePath);
		if (!f.exists()) {
			throw new FileNotFoundException(filePath);
		}
		ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
		BufferedInputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(f));
			int buf_size = 1024;
			byte[] buffer = new byte[buf_size];
			int len = 0;
			while (-1 != (len = in.read(buffer, 0, buf_size))) {
				bos.write(buffer, 0, len);
			}
			return bos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			bos.close();
		}
	}

	/**
	 * 文件是否存在
	 * @param filePath 
	 */
	public static boolean exists(String filePath) {
		try {
			File f = new File(filePath);
			if (f.isFile() && f.exists()) {
				return true;
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}

	/**
	 * 读取到字节数组2
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public static byte[] toByteArray2(String filePath) throws IOException {

		File f = new File(filePath);
		if (!f.exists()) {
			throw new FileNotFoundException(filePath);
		}

		FileChannel channel = null;
		FileInputStream fs = null;
		try {
			fs = new FileInputStream(f);
			channel = fs.getChannel();
			ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
			while ((channel.read(byteBuffer)) > 0) {
				// do nothing
				// System.out.println("reading");
			}
			return byteBuffer.array();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				channel.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				fs.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Mapped File way MappedByteBuffer 可以在处理大文件时，提升性能

	 * @return
	 * @throws IOException
	 */
	public static byte[] toByteArray3(String filePath) throws IOException {

		FileChannel fc = null;
		RandomAccessFile rf = null;
		try {
			rf = new RandomAccessFile(filePath, "r");
			fc = rf.getChannel();
			MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0, fc.size()).load();
			// System.out.println(byteBuffer.isLoaded());
			byte[] result = new byte[(int) fc.size()];
			if (byteBuffer.remaining() > 0) {
				// System.out.println("remain");
				byteBuffer.get(result, 0, byteBuffer.remaining());
			}
			return result;
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				rf.close();
				fc.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 转移文件 到 destinationFloderUrl 目录
	 * @param fileName
	 * @param destinationFloderUrl
	 * @return：文件名
	 */
	public static String transferToFolder(String fileName, String destinationFloderUrl) {
		File file = new File(fileName);
		File destFloder = new File(destinationFloderUrl);
		if (destFloder.exists()) {
			if (destFloder.isFile()) {
				return file.getName();
			}
		} else {
			if (!destFloder.mkdirs()) {
				return file.getName();
			}
		}
		//检查源文件是否合法
		if (file.isFile() && file.exists()) {
			String destinationFile = destinationFloderUrl + "/" + file.getName();
			if (!file.renameTo(new File(destinationFile))) {
				return file.getName();
			}
		} else {
			return file.getName();
		}
		return file.getName();
	}
}
